package com.rockcent.mall.lib.repository;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.rockcent.common.common.PageResult;
import com.rockcent.common.common.SQLPageDoing;
import com.rockcent.mall.lib.dto.UserMerchantDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

/**
 * Created by DK on 17/4/25.
 */
@Repository
public class UserMerchantRepositoryImpl implements UserMerchantRepositoryCustom {

    private static final Logger log = LoggerFactory.getLogger(UserMerchantRepositoryImpl.class);

    @Autowired
    private NamedParameterJdbcTemplate jdbcTemplate;

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public PageResult<UserMerchantDto> findMerchantChildAccountResourcePage(Long titleId, Long mallId, Long merchantId, PageResult page) {
        SQLPageDoing<UserMerchantDto> doing = (sql, fields, params, typeReferenceMap) -> {
            sql.append("select %s from user_merchant um left join merchant m on um.merchant_id = m.id left join mall ma on um.mall_id = ma.id where 1=1 ");
            if (titleId != null) {
                sql.append(" and um.title_id = :titleId");
                params.put("titleId", titleId);
            }
            sql.append(" and um.mall_id = :mallId");
            sql.append(" and um.merchant_id = :merchantId");
            params.put("mallId", mallId);
            params.put("merchantId", merchantId);
            fields.append("um.*, m.name merchantName, ma.name mallName");
        };
        return doing.go(page, UserMerchantDto.class, objectMapper, jdbcTemplate, log);
    }
}
